#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil

sys.path.append( os.path.dirname(__file__) )
curdir = os.path.dirname(__file__)

#SAKURA SERVERで必要な環境設定(VPSはコメントアウトする)
site.addsitedir(os.path.expanduser("_site-packages" ))

from config import *
from generator import *
from paneo import *

#from bs4 import BeautifulSoup
import sqlite3dbm

import web
web.ctx.homepath = '' 
web.config.debug = DEBUG 

from urls import URLS

#print "Content-type: text/html"
#print
#print "<html>"
#print "<center>Hello, PANEO</center>"
#print "</html>"
#exit(0)

#SESSION SQLite
import sqlite3
con = sqlite3.connect(SESSION_DB,isolation_level=None)

sessions_sql = """
CREATE TABLE sessions (
    session_id TEXT UNIQUE NOT NULL,
    atime TIMESTAMP,
    data TEXT
);
"""
cur = con.execute("SELECT * FROM sqlite_master WHERE type='table' and name='sessions'")
if cur.fetchone() == None: 
    con.execute(sessions_sql)
    con.commit()
con.close() 

#web.py app setting
app = web.application(URLS, globals())

db = web.database(dbn='sqlite', db=SESSION_DB)
store = web.session.DBStore(db, 'sessions')
session = web.session.Session(  app, 
                                store,
                                initializer={ 
                                    'loggedin':False,
                                    'admin':False,
                                    'count': 0, 
                                    'redirect_param':{},
                                  }, )

#PANEO PAGE DB Shelve xx ST
dic = sqlite3dbm.sshelve.open(PANEO_DB)

#PASSWORD
if dic.get('admin_password') is None :
    dic['admin_password'] = ADMIN_PASSWORD 
else:
    if dic.get('admin_password') != ADMIN_PASSWORD :
        dic['admin_password'] = ADMIN_PASSWORD 
if dic.get('user_password') is None :
    dic['user_password'] = USER_PASSWORD 
else:
    if dic.get('user_password') != ADMIN_PASSWORD :
        dic['user_password'] = USER_PASSWORD 

#PANEO SITECONFIG
if dic.get('siteconfig') is None :
    scfg = {}
    scfg['SITENAME'] = u'サイト名を入力してください'
    scfg['PAGEMAKE'] = u'CMS'
    scfg['CONTEXT'] = {}
    dic['siteconfig'] = scfg

##PANEO PAGES
if dic.get('pages') is None:
    pages = {}
    p = PaneoPage()
    p.IDX = 0
    p.PARENT = ''
    p.TEMPLATE = 'skelton'
    p.VIEWED = 1
    p.TITLE = 'HOME'
    p.LINK = ''
    p.CONTEXT = ''
    pages['index'] = p
    dic['pages'] = pages

#PANEO FILEDS
if dic.get('fields') is None:
    dic['fields'] = {}

dic.close()
#PANEO PAGE DB Shelve xx EN 

def session_hook():
    web.ctx.session = session
app.add_processor(web.loadhook(session_hook))

#PANEO AUTH
def auth_app_processor(handle):
    if str( web.ctx.path ).startswith("/paneo/"):
        if not str( web.ctx.path ).startswith("/paneo/login/"):
            if not web.ctx.session.get('loggedin') :
                raise web.seeother('http://' + web.ctx.host + '/paneo/login/')
    return handle()
app.add_processor(auth_app_processor)

def notfound():
    return web.notfound("Sorry, the page you were looking for was not found.")
app.notfound = notfound

from mako.template import Template
class hello:
    def GET(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")
        return Template("hello ${data} paneo!").render(data="world")

#from beaker.cache import CacheManager
#from beaker.util import parse_cache_config_options
#
#cache_opts = {
#    'cache.type': 'file',
#    'cache.data_dir': PANEO_SITE_DATA_DIR + '/_paneo_data/_tmp/cache/data',
#    'cache.lock_dir': PANEO_SITE_DATA_DIR + '/_paneo_data/_tmp/cache/lock'
#}
#cache = CacheManager(**parse_cache_config_options(cache_opts))

#if not HTML_CACHE:
#cache.clear()


application = app.wsgifunc()
if __name__ == "__main__":
    app.run()

